package fer

import (
	"context"
	"time"

	"gitee.com/k3x/urlx"
	"gitee.com/k3x/urlx/codec/html"
)

func FromBOC(ctx context.Context) (result Rates, err error) {
	defer result.SetDuration(time.Now())
	result.From = "中国银行"

	var rates []struct {
		Name            string  `find:"td:nth-child(1)"` // 货币名称
		BuyingRate      float64 `find:"td:nth-child(2)"` // 汇买价
		CashBuyingRate  float64 `find:"td:nth-child(3)"` // 钞买价
		SellingRate     float64 `find:"td:nth-child(4)"` // 汇卖价
		CashSellingRate float64 `find:"td:nth-child(5)"` // 钞卖价
		MiddleRate      float64 `find:"td:nth-child(6)"` // 中间价
		PubTime         string  `find:"td:nth-child(7)"`
	}
	err = urlx.MacEdge(ctx).Url("https://www.boc.cn/sourcedb/whpj/index_1.html").
		HeaderWith(urlx.Referer("https://www.boc.cn")).
		Process(html.Struct(&rates, "table tr:has(td.pjrq)"))

	result.Data = make(map[string]Rate, len(rates))
	if len(rates) > 0 {
		for i, r := range rates {
			if i == 0 {
				result.UpdateAt, _ = time.ParseInLocation("2006.01.02 15:04:05", r.PubTime, locCST)
			}
			currency := GetCode(r.Name)
			result.Data[currency] = Rate{
				Name:            r.Name,
				Currency:        currency,
				BuyingRate:      r.BuyingRate,
				CashBuyingRate:  r.CashBuyingRate,
				SellingRate:     r.SellingRate,
				CashSellingRate: r.CashSellingRate,
				MiddleRate:      r.MiddleRate,
			}
		}
	}
	return
}
